
var generateGUID = (typeof (window.crypto) !== 'undefined' && typeof (window.crypto.getRandomValues) !== 'undefined') ? function() {
    var buf = new Uint16Array(8);
    window.crypto.getRandomValues(buf);
    var S4 = function(num) {
        var ret = num.toString(16);
        while (ret.length < 4) {
            ret = "0" + ret;
        }
        return ret;
    };
    return ( S4(buf[0]) + S4(buf[1]) + "-" + S4(buf[2]) + "-" + S4(buf[3]) + "-" + S4(buf[4]) + "-" + S4(buf[5]) + S4(buf[6]) + S4(buf[7])) ;
} : function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
};
var genUUID = function() {
    return generateGUID();
};

class WsClient {
	constructor(options) {
		//判断浏览器是否支持WebSocket
		var supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
		if (supportsWebSockets) {
		    //建立WebSocket连接（ip地址换成自己主机ip）
		    var ws = new WebSocket(options.socketUrl);
		    ws.onopen = function(){
		        //当WebSocket创建成功时，触发onopen事件
		        console.log("websocket连接成功");
		        if (options.onWSConnect) {
		        	options.onWSConnect();
		        }
		    }
		    ws.onmessage = function(e){
		        //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
		        //console.log("收到数据");
		        //console.log(e.data);
		        if (options.onmessage) {
		        	e.eventData = $.parseJSON(e.data);
		        	options.onmessage(e);
		        }
		    }
		    ws.onclose = function(e){
		        //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
		        console.log("websocket已断开");
		        if (options.onWSClose) {
		        	options.onWSClose();
		        }
		    }
		    ws.onerror = function(e){
		        //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
		        console.log("websocket发生错误"+e);
		        if (options.onWSError) {
		        	options.onWSError(e);
		        }
		    }
		} else {
		    console.log("您的浏览器不支持 WebSocket!");
		}
		this._ws_socket = ws;
		this.options = options;
	}
	
	_current_id = 1;
	call(method, params, success_cb, error_cb) {
        if (!params) {
            params = {};
        }
        if (!success_cb) {
            success_cb = function(e) {
                console.log("Success: ", e);
            };
        }
        if (!error_cb) {
            error_cb = function(e) {
                console.log("Error: ", e);
            };
        }
        if (this.options.sessid) {
            params.sessid = this.options.sessid;
        }
		var json = JSON.stringify({
            jsonrpc: "2.0",
            method:method,
            params:params,
            id: this._current_id++
        });
        try {
			this._ws_socket.send(json);
			success_cb();
		} catch (e) {
			error_cb(e);
		}
	}
	
    socketReady() {
        if (this._ws_socket === null || this._ws_socket.readyState > 1) {
            return false;
        }
        return true;
    };
    
    closeSocket() {
        if (this.socketReady()) {
            this._ws_socket.close();
        }
    };
}
